package com.xiaotu.filter;


import com.alibaba.fastjson.JSONObject;
import com.xiaotu.common.RsponseStatus;
import com.xiaotu.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户token验证
 *
 * @author zhangxiao
 * @create 2021-01-11 19:59
 */

public class UserTokenFilter extends OncePerRequestFilter {


    final Logger logger = LoggerFactory.getLogger(UserTokenFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        logger.debug("request uri:" + request.getRequestURI());
        logger.debug("request refer:" + request.getHeader("Referer"));
        logger.debug("request user-agent:" + request.getHeader("user-agent"));
        logger.debug("request Authorization:" + request.getHeader("Authorization"));
        if (null != request.getHeader("Authorization")) {
            logger.debug("开始执行过滤器验证是否携带：Authorization");
            boolean verifyToken = TokenUtil.verifyToken(TokenUtil.getCookie(request));
            if (verifyToken) {
                filterChain.doFilter(request, response);
            } else {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                JSONObject json = new JSONObject();
                json.put("msg", "token verify fail or expired !");
                json.put("data", "");
                json.put("code", RsponseStatus.HTTP_RES_CODE_422);
                response.getWriter().append(json.toJSONString());
            }
        } else {
            filterChain.doFilter(request, response);
        }

    }

}


